
let AliveTemplate = `
<table class="table table-striped">
  <thead class="thead-light">
    <tr>
        <th  scope="col">ID</th>
        <th  scope="col">IP</th>
        <th  scope="col">Status</th>
        <th  scope="col">Activity</th>
        <th  scope="col">today</th>
        <th  scope="col">操作</th>
    </tr>
  </thead>
  <tbody  v-if="loading">
    <tr><td colspan="9">数据加载中。。。请稍后。。。</td></tr>
  </tbody>
  <tbody v-else>
    <tr>
      <td>/</td>
      <td>总计:{{list.length}}台</td>
      <td>故障:{{total.bad}}</td>
      <td>活跃:{{total.activity}}</td>
      <td>{{total.count}}</td>
      <td>/</td>
    </tr>
    <tr v-if="list.length == 0" >
      <td cols=6>暂无数据</td>
    </tr>
    <tr v-for="item in list" >
      <td>{{item.index}}</td>
      <td>
        <div class="input-group">
          <input type="text" class="form-control" v-model="item.id" disabled>
          <div class="input-group-append">
            <button class="btn btn-outline-secondary" type="button" :data-clipboard-text="item.id">复制</button>
          </div>
        </div>
      </td>
      <td v-if="item.bad" style="background-color: rgba(240, 9, 9, 0.644);color:white">故障</td>
      <td v-else>正常</td>
      <td>{{item.time | formatDate}}</td>
      <td>{{item.count}}</td>
      <td> 
        <a @click="del(item.index, item.id)" href="javascript:void(0)">删除</a>
        <router-link :to="{name:'details', params: { id: item.id }}" >
           <a>详细</a> 
        </router-link >
      </td>
    </tr>
  </tbody>
  </table>
  `
const Alive = Vue.component('alive-list', {
  template: AliveTemplate,
  data () {
    return {list:[], loading: true, total:{}}
  },
  created () {
      this.fetchData()
  },
  mounted(){
    new ClipboardJS('.btn').on('success', e => {
      console.log('复制成功')
    });
  },
  methods: {
    del(index, id){
      $.get("/api/del", {id: index+"-"+id}, ()=>{
        this.fetchData()
      })
    },
    fetchData () {
      this.msgList = []
      $.getJSON("/api/alive", (data)=>{
        this.loading = false
        let count = 0;
        let bad = 0;
        let activity = 0;
        data.forEach(element => {
          if(Date.now() - element.time*1000 > 1000 * 60 * 15){
            element.bad = true
            bad = bad + 1
          }else{
            activity = activity + 1
          }
          count = count + ~~element.count
          let tempArr = element.id ? element.id.split('-') : []
          element.index = tempArr[0]
          element.id = tempArr[1]
        });
        this.total = {
          bad: bad,
          activity: activity,
          count: count
        }
        this.list = data

      }).fail(function(response) {
        if(response.statusCode == 401){
          alert("请登录")
          location.href = "/public/login.html"
        }else{
          alert(response.responseText)
        }
      })
    }
  }
})